package com.lwb.ztx.main.widget;

import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTabHost;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;

import com.lwb.ztx.R;
import com.lwb.ztx.bean.ProfileBean;
import com.lwb.ztx.bean.Profiles;
import com.lwb.ztx.lives.widget.LiveFragment;
import com.lwb.ztx.main.presenter.MainPresenter;
import com.lwb.ztx.main.presenter.MainPresenterImpl;
import com.lwb.ztx.main.view.MainView;
import com.lwb.ztx.news.widget.NewsFragment;
import com.lwb.ztx.user.widget.UserFragment;
import com.lwb.ztx.receiver.NetWorkStateReceiver;
import com.lwb.ztx.utils.LogUtils;
import com.lwb.ztx.videos.wedget.VideoFragment;

import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener,NetWorkStateReceiver.OnNetworkStateChangeListener,MainView {
    private FragmentTabHost mTabHost;
    private Class fragmentArray[] = {
            LiveFragment.class,
            NewsFragment.class,
            VideoFragment.class,
            UserFragment.class
    };
    private int iconArray[] = {
            R.drawable.main_tab_icon_live,
            R.drawable.main_tab_icon_news,
            R.drawable.main_tab_icon_video,
            R.drawable.main_tab_icon_self
    };
    private String titleArray[] = {
            "直播",
            "新闻",
            "视频",
            "我"
    };

    public static Profiles profiles;

    private long exitTime;

    private NetWorkStateReceiver netWorkStateReceiver;

    private boolean isNetConnect = true;

    private MainPresenter mainPresenter;

    @InjectView(R.id.main_reload_btn)
    View reloadBtn;
    @InjectView(R.id.main_net_disconnect_view)
    View netDisConnectView;

    @SuppressWarnings("ResourceAsColor")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mainPresenter = new MainPresenterImpl(this);
        initIntent();
        setContentView(R.layout.activity_main);
        ButterKnife.inject(this);
        refreshView();
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setVisibility(View.GONE);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

            }
        });

        fab.setVisibility(View.GONE);

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string
                .navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        drawer.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED); //禁用手势滑动

        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        initContentView();

        IntentFilter filter=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        netWorkStateReceiver = new NetWorkStateReceiver(this);
        registerReceiver(netWorkStateReceiver,filter);

    }

    private void initIntent() {
        profiles = (Profiles) this.getIntent().getSerializableExtra("profiles");
        if(profiles.getProfileBeanList().size() == 0) {
            isNetConnect = false;
        }
        LogUtils.d(profiles.getProfileBeanList().toString());
    }

    private void initContentView() {
        mTabHost = (FragmentTabHost) this.findViewById(R.id.tabhost);
        setupTabView();
    }

    private void refreshView(){
        if(!isNetConnect){
            netDisConnectView.setVisibility(View.VISIBLE);
        } else {
            netDisConnectView.setVisibility(View.GONE);
        }
    }

    private void setupTabView() {
        mTabHost.setup(this.getApplication(), getSupportFragmentManager(), R.id.realtabcontent);
        mTabHost.getTabWidget().setDividerDrawable(null);

        int count = fragmentArray.length;
        for (int i = 0; i < count; i++) {
            TabHost.TabSpec tabSpec = mTabHost.newTabSpec(titleArray[i]).setIndicator
                    (getTabItemView(i));
            if (i == 0) {
                Bundle args = new Bundle();
                args.putSerializable("param1", profiles);
                mTabHost.addTab(tabSpec, fragmentArray[i], args);
            } else {
                mTabHost.addTab(tabSpec, fragmentArray[i], null);
            }
            mTabHost.getTabWidget().getChildAt(i);
        }
    }

    private View getTabItemView(int index) {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View view = layoutInflater.inflate(R.layout.tab_bottom_nav, null);

        ImageView imageView = (ImageView) view.findViewById(R.id.iv_icon);
        imageView.setImageResource(iconArray[index]);

        TextView textView = (TextView) view.findViewById(R.id.tv_icon);
        textView.setText(titleArray[index]);

        return view;
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - exitTime) > 2000)  //System.currentTimeMillis()无论何时调用，肯定大于2000
            {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @OnClick(R.id.main_reload_btn)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_reload_btn:
//                mainPresenter.getTotalProfile();
//                view.setClickable(false);
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(netWorkStateReceiver);
    }

    @Override
    public void onNetWorkConnected() {
        isNetConnect = true;
    }

    @Override
    public void onNetWorkDisConnected() {

    }

    @Override
    public void onLoadingFinish(List<ProfileBean> profileBeanList) {
        LogUtils.i(profileBeanList.toString());
        this.profiles.setProfileBeanList(profileBeanList);
        refreshView();
//        mTabHost.removeAllViews();
        setupTabView();
        List<Fragment> fragments = getSupportFragmentManager().getFragments();
        if(fragments.size() > 0) {
            if(fragments.get(0) instanceof NewsFragment) {
                NewsFragment newsFragment = (NewsFragment) fragments.get(0);
                LogUtils.i("#### " + newsFragment.getNewsProfiles());
            }
        }

        reloadBtn.setClickable(true);
    }
}
